// Next.js API路由 - PTZ代理
export async function GET(request, { params }) {
  try {
    const { path } = params;
    const { searchParams } = new URL(request.url);
    
    // 构建目标URL
    const wvpBaseUrl = process.env.WVP_BASE_URL || 'http://222.222.25.198:18082';
    const apiPath = Array.isArray(path) ? path.join('/') : path;
    
    // 修正：确保不会重复api/front-end路径
    let targetUrl;
    if (apiPath.startsWith('api/front-end/')) {
      targetUrl = `${wvpBaseUrl}/${apiPath}`;
    } else {
      targetUrl = `${wvpBaseUrl}/api/front-end/${apiPath}`;
    }
    
    // 添加查询参数
    const urlWithParams = new URL(targetUrl);
    searchParams.forEach((value, key) => {
      urlWithParams.searchParams.set(key, value);
    });

    console.log('代理请求到:', urlWithParams.toString());

    // 获取API Key认证
    const apiKey = request.headers.get('x-api-key') || request.headers.get('api-key') || request.headers.get('authorization');
    
    // 根据WVP的认证机制，API Key可以通过多种方式传递
    const requestHeaders = {
      'Content-Type': 'application/json',
      'User-Agent': 'WRPlayer-PTZ-Proxy/1.0'
    };
    
    if (apiKey) {
      const cleanApiKey = apiKey.replace('Bearer ', '').replace('ApiKey ', '');
      
      // 根据你的WVP配置，使用 api-key 请求头
      requestHeaders['api-key'] = cleanApiKey;
      
      // 也尝试其他可能的认证方式作为备用
      requestHeaders['X-API-Key'] = cleanApiKey;
      requestHeaders['Authorization'] = `Bearer ${cleanApiKey}`;
      
      console.log('设置API Key认证头：', 'api-key');
    }
    
    console.log('最终请求URL:', urlWithParams.toString());
    console.log('请求头包含API Key:', !!apiKey);
    
    // 转发请求到wvp服务
    const response = await fetch(urlWithParams.toString(), {
      method: 'GET',
      headers: requestHeaders,
      timeout: 10000 // 10秒超时
    });

    console.log('WVP服务响应状态:', response.status, response.statusText);

    if (!response.ok) {
      const errorText = await response.text().catch(() => '无法读取错误响应');
      console.error('WVP服务错误响应:', errorText);
      throw new Error(`WVP服务响应错误: ${response.status} ${response.statusText}\n响应内容: ${errorText}`);
    }

    const contentType = response.headers.get('content-type');
    let data;
    
    if (contentType && contentType.includes('application/json')) {
      data = await response.json();
    } else {
      const text = await response.text();
      console.log('非JSON响应:', text);
      data = { message: text, success: true };
    }
    
    return Response.json(data, {
      status: 200,
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      }
    });

  } catch (error) {
    console.error('PTZ代理请求失败:', {
      error: error.message,
      stack: error.stack,
      url: request.url,
      params: params
    });
    
    // 根据错误类型返回不同的状态码
    let status = 500;
    let errorMessage = error.message || '代理请求失败';
    
    if (error.name === 'TypeError' && error.message.includes('fetch')) {
      status = 503;
      errorMessage = 'WVP服务不可访问，请检查服务地址和网络连接';
    } else if (error.message.includes('timeout')) {
      status = 504;
      errorMessage = 'WVP服务响应超时';
    }
    
    return Response.json(
      { 
        code: -1, 
        msg: errorMessage,
        error: error.toString(),
        debug: {
          requestUrl: request.url,
          params: params,
          timestamp: new Date().toISOString()
        }
      },
      { 
        status,
        headers: {
          'Access-Control-Allow-Origin': '*',
          'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
          'Access-Control-Allow-Headers': 'Content-Type, Authorization',
        }
      }
    );
  }
}

// 处理OPTIONS预检请求
export async function OPTIONS() {
  return new Response(null, {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    },
  });
}